<?php

namespace app\shop\controller;

use Jssdk\jssdk;
use think\facade\Db;

class H5 extends Base
{
    /**
     * 获取h5首页数据
     */
    public function getIndexData()
    {
        $shop = Db::name('shop')
            ->where('id', self::$shop['id'])
            ->find();

        // 今日收款
        $income_total = 0;
        $income_wxpay = 0;
        $income_alipay = 0;
        $count_total = 0;
        $count_wxpay = 0;
        $count_alipay = 0;

        $start_time = strtotime(date('Y-m-d'));
        $list = Db::name('order')
            ->where([
                ['shop_id', '=', self::$shop['id']],
                ['status', '=', 1],
                ['is_refund', '=', 0],
                ['pay_time', '>', $start_time]
            ])
            ->field('total_fee,pay_type')
            ->select()
            ->toArray();
        foreach ($list as $v) {
            $income_total += $v['total_fee'];
            $count_total++;
            if ($v['pay_type'] == 'wxpay') {
                $income_wxpay += $v['total_fee'];
                $count_wxpay++;
            } elseif ($v['pay_type'] == 'alipay') {
                $income_alipay += $v['total_fee'];
                $count_alipay++;
            }
        }

        return successJson([
            'shop' => [
                'title' => $shop['title'],
                'phone' => $shop['link_phone'],
                'avatar' => mediaUrl('/static/img/avatar-shop.png', true),
            ],
            'income' => [
                'income_total' => $income_total / 100,
                'income_wxpay' => $income_wxpay / 100,
                'income_alipay' => $income_alipay / 100,
                'count_total' => $count_total,
                'count_wxpay' => $count_wxpay,
                'count_alipay' => $count_alipay
            ],
            'notice' => []
        ]);
    }

    /**
     * 获取jssdk参数
     */
    public function getJssdkData()
    {
        //获得jsapi的参数，signPackage
        $payConfig = getShopPayConfig(self::$shop['id'], 'wxpay');
        if (!$payConfig['status'] || empty($payConfig['appid'])) {
            $server = Db::name('server')
                ->where('type', 'wxpay')
                ->field('config')
                ->find();
            if (!empty($server)) {
                $payConfig = @json_decode($server['config'], true);
            }
        }
        if (empty($payConfig['appid'])) {
            return errorJson('请先配置支付参数');
        }
        $jssdk = new jssdk($payConfig['appid'], $payConfig['appsecret']);
        $url = input('url', '', 'trim');
        $signPackage = $jssdk->getSignPackage($url);

        return successJson([
            'signPackage' => $signPackage
        ]);
    }

    public function getChartData()
    {
        $today = date('Y-m-d');
        $where = [
            ['shop_id', '=', self::$shop['id']],
            ['status', '=', 1],
            ['is_refund', '=', 0]
        ];

        $timeArr = [];
        $countArr = [];
        $amountArr = [];
        for ($i = 15; $i >= 0; $i--) {
            $start_time = strtotime($today . "-{$i} day");
            $end_time = $start_time + 24 * 3600 - 1;

            $where2 = $where;
            $where2[] = ['pay_time', 'between', [$start_time, $end_time]];
            $list = Db::name('order')
                ->where($where2)
                ->field('total_fee,pay_type')
                ->select()
                ->toArray();
            $wxpayTotal = 0;
            $alipayTotal = 0;
            $allTotal = 0;
            foreach ($list as $v) {
                if ($v['pay_type'] == 'wxpay') {
                    $wxpayTotal += $v['total_fee'];
                } elseif ($v['pay_type'] == 'alipay') {
                    $alipayTotal += $v['total_fee'];
                }
                $allTotal += $v['total_fee'];
            }

            $timeArr[] = date('m-d', $start_time);
            $wxpayArr[] = $wxpayTotal / 100;
            $alipayArr[] = $alipayTotal / 100;
            $allArr[] = $allTotal / 100;
        }

        return successJson([
            'times' => $timeArr,
            'wxpay' => $wxpayArr,
            'alipay' => $alipayArr,
            'all' => $allArr
        ]);
    }

    public function getPaySetting()
    {
        $shop = Db::name('shop')
            ->where('id', self::$shop['id'])
            ->field('alipay_config,wxpay_config')
            ->find();
        // 微信配置
        if($shop['wxpay_config']) {
            $wxpayConfig = json_decode($shop['wxpay_config'], true);
            $wxpay = [
                'status' => $wxpayConfig['wxpay_status'] . '',
                'mch_id' => isset($wxpayConfig['wxpay_mch_id']) ? $wxpayConfig['wxpay_mch_id'] : '',
                'rate' => isset($wxpayConfig['wxpay_rate']) ? $wxpayConfig['wxpay_rate'] : '',
                'jinjian_status' => ''
            ];
        } else {
            $wxpay = [
                'status' => '0',
                'mch_id' => '',
                'rate' => '',
                'jinjian_status' => ''
            ];
        }

        $jinjianWxpay = Db::name('jinjian_wxpay')
            ->where('shop_id', self::$shop['id'])
            ->find();
        if ($jinjianWxpay) {
            $wxpay['jinjian_status'] = $jinjianWxpay['applyment_state'];
            $wxpay['account_name'] = $jinjianWxpay['account_name'];
            $wxpay['account_bank'] = $jinjianWxpay['account_bank'] == '其他银行' ? $jinjianWxpay['bank_name'] : $jinjianWxpay['account_bank'];
            $wxpay['account_number'] = $jinjianWxpay['account_number'];
            $wxpay['add_time'] = date('Y-m-d H:i:s', $jinjianWxpay['add_time']);
            $wxpay['update_time'] = $jinjianWxpay['update_time'] ? date('Y-m-d H:i:s', $jinjianWxpay['update_time']) : '-';
        }

        // 支付宝配置
        if($shop['alipay_config']) {
            $alipayConfig = json_decode($shop['alipay_config'], true);
            $alipay = [
                'status' => $alipayConfig['alipay_status'] . '',
                'pid' => isset($alipayConfig['alipay_pid']) ? $alipayConfig['alipay_pid'] : '',
                'auth_token' => isset($alipayConfig['alipay_token']) ? $alipayConfig['alipay_token'] : '',
                'rate' => isset($alipayConfig['alipay_rate']) ? $alipayConfig['alipay_rate'] : '',
                'jinjian_status' => ''
            ];
        } else {
            $alipay = [
                'status' => '',
                'pid' => '',
                'auth_token' => '',
                'rate' => '',
                'jinjian_status' => ''
            ];
        }
        $jinjianAlipay = Db::name('jinjian_alipay')
            ->where('shop_id', self::$shop['id'])
            ->find();
        if ($jinjianAlipay) {
            $alipay['jinjian_status'] = $jinjianAlipay['order_status'];
            $alipay['account'] = $jinjianAlipay['account'];
            $alipay['add_time'] = date('Y-m-d H:i:s', $jinjianAlipay['add_time']);
            $jinjianAlipay['update_time'] = $jinjianAlipay['update_time'] ? $jinjianAlipay['update_time'] : $jinjianAlipay['add_time'];
            $alipay['update_time'] = $jinjianAlipay['update_time'] ? date('Y-m-d H:i:s', $jinjianAlipay['update_time']) : '-';
        }

        return successJson([
            'wxpay' => $wxpay,
            'alipay' => $alipay
        ]);
    }

    /**
     * 把支付宝进件的资料配置到支付参数里
     */
    public function openAlipay()
    {
        $jinjian = Db::name('jinjian_alipay')
            ->where('shop_id', self::$shop['id'])
            ->find();
        if (!$jinjian || $jinjian['order_status'] != 'MERCHANT_CONFIRM_SUCCESS') {
            return errorJson('开通尚未完成，请完成后再操作');
        }
        // 配置商家支付宝支付参数
        $alipayConfig = [
            'alipay_status' => 1,
            'alipay_type' => 'server',
            'alipay_server_id' => $jinjian['server_id'],
            'alipay_pid' => $jinjian['merchant_pid'],
            'alipay_token' => $jinjian['app_auth_token'],
            'alipay_rate' => !empty($jinjian['activities_rate']) ? $jinjian['activities_rate'] : 0.38
        ];
        Db::name('shop')
            ->where('id', self::$shop['id'])
            ->update([
                'alipay_config' => json_encode($alipayConfig)
            ]);
        return successJson('', '已开启支付宝收款');
    }

    /**
     * 把微信进件的资料配置到支付参数里
     */
    public function openWxpay()
    {
        $jinjian = Db::name('jinjian_wxpay')
            ->where('shop_id', self::$shop['id'])
            ->find();
        if (!$jinjian || $jinjian['applyment_state'] != 'APPLYMENT_STATE_FINISHED') {
            return errorJson('开通尚未完成，请完成后再操作');
        }
        // 配置商家微信支付参数
        $wxpayConfig = [
            'wxpay_status' => 1,
            'wxpay_type' => 'server',
            'wxpay_server_id' => $jinjian['server_id'],
            'wxpay_mch_id' => $jinjian['sub_mchid'],
            'wxpay_rate' => str_replace('%', '', $jinjian['activities_rate'])
        ];
        Db::name('shop')
            ->where('id', self::$shop['id'])
            ->update([
                'wxpay_config' => json_encode($wxpayConfig)
            ]);
        return successJson('', '已开启微信收款');
    }

    /**
     * 切换支付宝收款状态
     */
    public function switchAlipayStatus()
    {
        $val = input('val', 0, 'intval');
        $config = Db::name('shop')
            ->where('id', self::$shop['id'])
            ->value('alipay_config');
        if (!$config) {
            $config = '[]';
        }
        $config = json_decode($config, true);
        $config['alipay_status'] = $val ? 1 : 0;

        Db::name('shop')
            ->where('id', self::$shop['id'])
            ->update([
                'alipay_config' => json_encode($config)
            ]);
        return successJson('', '保存成功');
    }

    /**
     * 切换微信收款状态
     */
    public function switchWxpayStatus()
    {
        $val = input('val', 0, 'intval');
        $config = Db::name('shop')
            ->where('id', self::$shop['id'])
            ->value('wxpay_config');
        if (!$config) {
            $config = '[]';
        }
        $config = json_decode($config, true);
        $config['wxpay_status'] = $val ? 1 : 0;

        Db::name('shop')
            ->where('id', self::$shop['id'])
            ->update([
                'wxpay_config' => json_encode($config)
            ]);
        return successJson('', '保存成功');
    }
}
